#include "Game.h"
#include "SceneMain.h"
#include "SDL2/SDL_image.h"

Game::Game()
{
    // init();

}

Game::~Game()
{
    clean();
}

void Game::run()
{
    while(isRunning)
    {
        auto frameStart = SDL_GetTicks();
        SDL_Event event;
        handleEvents(&event); // 处理事件
        update(deltaTime);    // 逻辑更新
        render();             // 渲染绘制
        auto diff = SDL_GetTicks() - frameStart;
        if (diff < frameTime)
        {
            SDL_Delay(frameTime - diff);
            deltaTime = frameTime / 1000.0f;
        } 
        else
        {
            deltaTime = diff / 1000.0f;
        }
    }

}

void Game::init()
{
    frameTime = 1000 / FPS; // 计算每帧时间
    // SDL初始化
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
    {
        SDL_LogError(SDL_LOG_CATEGORY_ERROR, "SDL Could not initialize! SDL_Error: %s\n", SDL_GetError());
        isRunning = false;
    }

    // 创建窗口
    window = SDL_CreateWindow("Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, windowWidth, windowHeight, SDL_WINDOW_SHOWN);
    if (window == nullptr)
    {
        SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Window could not be created! SDL_Error: %s\n", SDL_GetError());
        isRunning = false;
    }
    // 创建渲染器
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    if (renderer == nullptr)
    {
        SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Renderer could not be created! SDL_Error: %s\n", SDL_GetError());
        isRunning = false;
    }

    // 初始化SDL_image
    if (IMG_Init(IMG_INIT_PNG) != IMG_INIT_PNG) {
        SDL_LogError(SDL_LOG_CATEGORY_ERROR, "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError());
        isRunning = false;
    }

    currentScene = new SceneMain(); // 创建主场景
    currentScene->init();            // 初始化主场景

}

void Game::clean()
{
    if(currentScene != nullptr)
    {
        currentScene->clean();
        delete currentScene;
    }

    //清理SDL_Image
    IMG_Quit();
    
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit(); 
}

void Game::changeScene(Scene *scene)
{
    if (currentScene != nullptr)
    {
        currentScene->clean();
        delete currentScene;
    }
    currentScene = scene;
    currentScene->init();   
    
}

void Game::handleEvents(SDL_Event* event)
{
    // 轮询事件
    while (SDL_PollEvent(event))
    {
        // 处理退出事件
        if(event->type == SDL_QUIT)
        {
            isRunning = false;
        }
        
        currentScene->handleEvents(event); // 处理事件
    }
}

void Game::update(float deltaTime)
{
    currentScene->update(deltaTime);  // 逻辑更新
}

void Game::render()
{
    // 清空渲染器
    SDL_RenderClear(renderer);
    currentScene->render();             // 渲染绘制
    // 更新渲染器
    SDL_RenderPresent(renderer);
}
